/**
 * 用户服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { Role } from '../role/entities/role.entity';
import { QueryUserDto } from './dto/query-user.dto';
import { IS_DATA_URI } from 'class-validator';

// 定义安全的用户信息类型
export interface SafeUserInfo extends Omit<User, 'password'> {
  roles: Role[];
}

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  /**
   * 创建用户
   * @param createUserDto 创建用户数据传输对象
   * @returns Promise<User> 创建的用户信息
   */
  async create(createUserDto: CreateUserDto): Promise<User> {
    const user = this.userRepository.create(createUserDto);
    return await this.userRepository.save(user);
  }

  /**
   * 获取所有未删除的用户
   * @returns Promise<User[]> 用户列表
   */
  async findAll(query: QueryUserDto): Promise<[SafeUserInfo[], number]> {
    const { page, pageSize, username, email, status } = query;

    // 构建查询条件
    const where: any = {
      is_deleted: 0,
    };

    if (username) {
      where.username = Like(`%${username}%`);
    }
    if (email) {
      where.email = Like(`%${email}%`);
    }
    if (status !== undefined) {
      where.status = status;
    }

    // 使用 Repository 的 findAndCount 方法
    const [items, total] = await this.userRepository.findAndCount({
      where,
      relations: ['roles'],
      order: {
        created_at: 'DESC',
      },
      skip: (page - 1) * pageSize,
      take: pageSize,
    });

    // 处理返回数据，移除敏感信息
    const safeItems = items.map(({ password, ...rest }) => ({
      ...rest,
      roles: rest.roles || [],
    })) as SafeUserInfo[];

    return [safeItems, total];
  }

  /**
   * 根据ID获取未删除的用户
   * @param id 用户ID
   * @returns Promise<User> 用户信息
   * @throws NotFoundException 用户不存在时抛出异常
   */
  async findOne(id: number): Promise<User | undefined> {
    if (!id || isNaN(id)) {
      throw new BadRequestException('Invalid user ID');
    }
    
    const user = await this.userRepository.findOne({
      where: {
        id,
        is_deleted: 0,
      },
    });

    if (!user) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }

    return user;
  }

  /**
   * 更新用户信息
   * @param id 用户ID
   * @param updateUserDto 更新用户数据传输对象
   * @returns Promise<User> 更新后的用户信息
   */
  async update(id: number, updateUserDto: UpdateUserDto): Promise<User> {
    const user = await this.findOne(id);
    if (!user) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }
    Object.assign(user, updateUserDto);
    return await this.userRepository.save(user);
  }

  /**
   * 软删除用户
   * @param id 用户ID
   */
  async remove(id: number): Promise<void> {
    const user = await this.findOne(id);
    if (!user) {
      throw new NotFoundException(`User with ID ${id} not found`);
    }
    user.is_deleted = 1;
    await this.userRepository.save(user);
  }

  /**
   * 根据用户名查找用户
   * @param username 用户名
   * @returns Promise<User> 用户信息
   */
  async findByUsername(username: string): Promise<User | null> {
    if (!username) {
      throw new BadRequestException('Username is required');
    }

    return await this.userRepository.findOne({
      where: { 
        username,
        is_deleted: 0 
      },
    });
  }

  /**
   * 获取用户信息
   * @returns Promise<User> 用户信息
   */
  async getUserInfo(userId: number): Promise<User> {
    if (!userId || isNaN(userId)) {
      throw new BadRequestException('Invalid user ID');
    }

    const user = await this.userRepository.findOne({
      where: { 
        id: userId,
        is_deleted: 0 
      },
      relations: ['roles', 'roles.permissions'], // 加载角色和权限关系
    });

    if (!user) {
      throw new NotFoundException(`User not found`);
    }

    return user;
  }

  /**
   * 获取用户详细信息（包含角色、权限等）
   */
  async getInfo(userId: number) {
    if (!userId || isNaN(userId)) {
      throw new BadRequestException('Invalid user ID');
    }

    const user = await this.userRepository.findOne({
      where: { 
        id: userId,
        is_deleted: 0 
      },
      relations: ['roles', 'roles.permissions'],
    });

    if (!user) {
      throw new NotFoundException(`User not found`);
    }

    // 转换为前端需要的格式
    return {
      userId: user.id,
      username: user.username,
      // realName: user.real_name,
      // avatar: user.avatar,
      // desc: user.description,
      homePath: '/dashboard',
      roles: user.roles.map(role => ({
        roleName: role.name,
        value: role.code,
      })),
      permissions: user.roles.reduce((acc, role) => {
        return [...acc, ...role.permissions.map(p => p.code)];
      }, []),
    };
  }
} 